﻿/*
<File>
	<Copyright>Copyright © 2007, Outcoder. All rights reserved.</Copyright>
	<License see="//License.txt"/>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com"/>
	<CreationDate>2007/11/19 20:00</CreationDate>
	<LastSubmissionDate>$Date: $</LastSubmissionDate>
	<Version>$Revision: $</Version>
</File>
*/

using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Provider;

namespace Outcoder.Logging
{
	/// <summary>
	/// The default log strategy provider.
	/// This should be sufficient in most cases.
	/// </summary>
	class LogStrategyProvider : ProviderBase, ILogStrategyProvider
	{
		ILogStrategy logStrategy;
		
		public ILogStrategy LogStrategy
		{
			get
			{
				return logStrategy;
			}
			internal set
			{
				logStrategy = value;
			}
		}

		public override void Initialize(string name, NameValueCollection config)
		{
			base.Initialize(name, config);

			string providerTypeName = config["LogStrategy"];
			if (string.IsNullOrEmpty(providerTypeName))
			{
				ThrowMissingPropertyException("LogStrategy");
			}

			config.Remove("LogStrategy");

			try
			{
				Type type = Type.GetType(providerTypeName);
				logStrategy = (ILogStrategy)Activator.CreateInstance(type);
			}
			catch (Exception ex)
			{
				throw new ConfigurationErrorsException("LogStrategy is missing or of wrong type.", ex);
			}
		}

		public void Initialize(string name, Type logStrategyType)
		{
			base.Initialize(name, new NameValueCollection());

			try
			{
				logStrategy = (ILogStrategy)Activator.CreateInstance(logStrategyType);
			}
			catch (Exception ex)
			{
				throw new ConfigurationErrorsException("Unable to instanciate type " + logStrategyType, ex);
			}
		}

		/// <summary>
		/// Throws a missing property exception.
		/// </summary>
		/// <param name="propertyName">Name of the property.</param>
		static protected void ThrowMissingPropertyException(string propertyName)
		{
			string message = string.Format("Empty or missing property \"{0}\".", propertyName);
			throw new ProviderException(message);
		}
	}
}
